/*
 * Question_AnswerView.java
 */

package question_answer;

import com.sun.java.swing.plaf.windows.resources.windows;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import jess.Rete;
import java.awt.Image;
import java.awt.*;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.KeyStroke;
import sun.awt.image.ToolkitImage;
import sun.io.Converters;

/**
 * The application's main frame.
 */
public class Question_AnswerView extends FrameView {

   
    public Question_AnswerView(SingleFrameApplication app) {
        super(app);

        initComponents();

        statusPanel.setVisible(false);        
        //--------------- Programmer----------
            jessEngine = new JessRuleDeftemplate();
            jessEngine.MakeTemplate();
            jessEngine.MakeRule();
            reteEngine = jessEngine.getRete_Engine();
            this.addSentence = new AddWorkingMemory();
            this.parserSentence = new Parser();

        //-----------------------------------
        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = Question_AnswerApp.getApplication().getMainFrame();
            aboutBox = new Question_AnswerAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        Question_AnswerApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        textStatement = new javax.swing.JTextField();
        textQuestion = new javax.swing.JTextField();
        textAnswer = new javax.swing.JTextField();
        labelStatement = new javax.swing.JLabel();
        labelQuestion = new javax.swing.JLabel();
        labelAnswer = new javax.swing.JLabel();
        buttonAnswer = new javax.swing.JButton();
        progressBar = new javax.swing.JProgressBar();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();

        mainPanel.setName("mainPanel"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(question_answer.Question_AnswerApp.class).getContext().getResourceMap(Question_AnswerView.class);
        textStatement.setFont(resourceMap.getFont("txtStatement.font")); // NOI18N
        textStatement.setText(resourceMap.getString("txtStatement.text")); // NOI18N
        textStatement.setName("txtStatement"); // NOI18N
        textStatement.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                textStatementMouseClicked(evt);
            }
        });

        textQuestion.setFont(resourceMap.getFont("txtQuestion.font")); // NOI18N
        textQuestion.setText(resourceMap.getString("txtQuestion.text")); // NOI18N
        textQuestion.setName("txtQuestion"); // NOI18N
        textQuestion.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                textQuestionMouseClicked(evt);
            }
        });
        textQuestion.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                textQuestionKeyPressed(evt);
            }
        });

        textAnswer.setFont(resourceMap.getFont("txtAnswer.font")); // NOI18N
        textAnswer.setText(resourceMap.getString("txtAnswer.text")); // NOI18N
        textAnswer.setName("txtAnswer"); // NOI18N

        labelStatement.setFont(resourceMap.getFont("labelStatement.font")); // NOI18N
        labelStatement.setText(resourceMap.getString("labelStatement.text")); // NOI18N
        labelStatement.setName("labelStatement"); // NOI18N

        labelQuestion.setFont(resourceMap.getFont("labelQuestion.font")); // NOI18N
        labelQuestion.setText(resourceMap.getString("labelQuestion.text")); // NOI18N
        labelQuestion.setName("labelQuestion"); // NOI18N

        labelAnswer.setFont(resourceMap.getFont("labelAnswer.font")); // NOI18N
        labelAnswer.setText(resourceMap.getString("labelAnswer.text")); // NOI18N
        labelAnswer.setName("labelAnswer"); // NOI18N

        buttonAnswer.setFont(resourceMap.getFont("btnAnswer.font")); // NOI18N
        buttonAnswer.setText(resourceMap.getString("btnAnswer.text")); // NOI18N
        buttonAnswer.setName("btnAnswer"); // NOI18N
        buttonAnswer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonAnswerActionPerformed(evt);
            }
        });

        progressBar.setBorderPainted(false);
        progressBar.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        progressBar.setIndeterminate(true);
        progressBar.setName("current"); // NOI18N
        progressBar.setString(resourceMap.getString("current.string")); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(labelStatement)
                            .addComponent(labelQuestion)
                            .addComponent(textStatement, javax.swing.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE)
                            .addComponent(textQuestion, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE)))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(labelAnswer))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(textAnswer, javax.swing.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                        .addGap(125, 125, 125)
                        .addComponent(buttonAnswer, javax.swing.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE)
                        .addGap(107, 107, 107)
                        .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelStatement)
                .addGap(3, 3, 3)
                .addComponent(textStatement, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(labelQuestion)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(textQuestion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(labelAnswer)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(textAnswer, javax.swing.GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE)
                .addGap(27, 27, 27)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(buttonAnswer, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(15, 15, 15))
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(question_answer.Question_AnswerApp.class).getContext().getActionMap(Question_AnswerView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 350, Short.MAX_VALUE)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel))
                .addGap(11, 11, 11))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    private void buttonAnswerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAnswerActionPerformed
        buttonAnswer.enable(false);                       
        try{
            
            this.reteEngine.reset();
            String strStatement = this.textStatement.getText();
            String strQuestion = this.textQuestion.getText();
            if(strStatement.isEmpty()){
               JOptionPane.showMessageDialog(new JLabel(), "Statement can't null","Message",JOptionPane.ERROR_MESSAGE);
               return;
            }
            if(strQuestion.isEmpty()){
                JOptionPane.showMessageDialog(new JLabel(), "Question can't null","Message",JOptionPane.ERROR_MESSAGE);
                return;
            }
            String parserStatement = this.parserSentence.MakeParser(strStatement);
            String parserQuestion = this.parserSentence.MakeParser(strQuestion);
            this.addSentence.CreateListTemplate(parserStatement, 1);
            this.addSentence.CreateListTemplate(parserQuestion,0);
            
            this.addSentence.AddFact(this.reteEngine);
            this.reteEngine.run();
            String strAnswer = this.jessEngine.Answer();
            if(strAnswer.isEmpty())
            {
                JOptionPane.showMessageDialog(new JLabel(), "Can't find answer. Maybe:"
                        + "\nSystem don't have rule for this question"
                        + "\nStatement and question don't accord","Message",JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            System.out.println("Answer:" + strAnswer);
            this.textAnswer.setText(strAnswer);            
            buttonAnswer.enable(true);
        }
        catch(Exception e)
        {
            System.out.println(e.toString());
        }
        //progressBar.setIndeterminate(false);
        textStatement.setFocusable(true);
        textStatement.selectAll();
        
    }//GEN-LAST:event_buttonAnswerActionPerformed
    // variable of programmer. Jess rule.
    Parser parserSentence;
    AddWorkingMemory addSentence;
    Rete reteEngine;
    JessRuleDeftemplate jessEngine;

    private void textQuestionKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textQuestionKeyPressed
        if (evt.getKeyCode() == 10) {
            buttonAnswerActionPerformed(null);
        }
       
    }//GEN-LAST:event_textQuestionKeyPressed

    private void textStatementMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_textStatementMouseClicked
        textStatement.selectAll();
    }//GEN-LAST:event_textStatementMouseClicked

    private void textQuestionMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_textQuestionMouseClicked
        textQuestion.selectAll();
    }//GEN-LAST:event_textQuestionMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonAnswer;
    private javax.swing.JLabel labelAnswer;
    private javax.swing.JLabel labelQuestion;
    private javax.swing.JLabel labelStatement;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JTextField textAnswer;
    private javax.swing.JTextField textQuestion;
    private javax.swing.JTextField textStatement;
    // End of variables declaration//GEN-END:variables

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;
}
